<?php


namespace app\controller;


use app\BaseController;
use app\model\User;
use app\Request;
use think\cache\driver\Redis;
use think\facade\Cache;
use think\facade\Db;

class LoginController extends  BaseController
{
    public function login(Request  $request){
        $param = $request->param(['pwd','email']);
        $this->validate($param,'UserValidate.login');

        $userInfo = User::where('email' ,'=', $param['email'])->find();
        if (empty($userInfo)){
            return $this->returnJson(self::USER_ERROR,'邮箱或密码错误');
        }
        if ($userInfo['password'] != md5($param['pwd'])){
            return $this->returnJson(self::USER_ERROR,'邮箱或密码错误');
        }

        $token = $this->makeToken($userInfo['id']);
        if (!Cache::store('redis')->set($token,$userInfo,24*60*60)){
            return $this->returnJson(self::SERVER_ERROR,'服务器错误，请重试');
        }

        return $this->returnJson(self::SUCCESS,'登入成功',$token);
    }

    public function  signOut(Request $request){
        $token = $request->header('Authorization', '');

        if (!Cache::store('redis')->delete($token)){
            return $this->returnJson(self::SERVER_ERROR,'服务器错误，请重试');
        }

        return $this->returnJson(self::SUCCESS,'退出成功，跳转首页');
    }
}